from fastapi import APIRouter, Depends, Query
from dependencies import get_mysql_db, require_login
from databases import Database
from schema.dao.drive_action import FeedbackInDb, FeedbackConverted, ViolationInDb, ViolationConverted, ComplaintInDb, ComplaintConverted
from schema.resp import RestfulModel, PageInfo
from sqlmodel import select, desc, func
# from sqlalchemy import func
from typing import Optional, List
from service.post_process_service import PostProcessFeedback, PostProcessViolation, PostProcessComplaint


drive_action_detail_router = APIRouter(prefix='/driver-behavior/detail',
                                       dependencies=[Depends(require_login, )],
                                       tags=['驾驶行为感知-详细信息'])


@drive_action_detail_router.get('/feedback',
                                response_model=RestfulModel[PageInfo[FeedbackConverted]],
                                summary='异常驾驶行为')
async def get_user_feedback(page_num: Optional[int] = Query(1, title='页号', alias='pageNum'),
                            page_size: Optional[int] = Query(50, title='一页多少数据', alias='pageSize'),
                            mysql_db: Database = Depends(get_mysql_db)):
    offset = (page_num - 1) * page_size
    statement = select(FeedbackInDb).order_by(desc(FeedbackInDb.time)).offset(offset).limit(page_size)
    feedback_list = await mysql_db.fetch_all(statement)
    total_cnt = await mysql_db.fetch_val(f'SELECT COUNT(*) FROM {FeedbackInDb.__tablename__};')
    feedback_list = [PostProcessFeedback.convert_feedback(FeedbackInDb(**feedback)) for feedback in feedback_list]
    return RestfulModel.success(PageInfo(total=total_cnt, list=feedback_list))


@drive_action_detail_router.get('/violation',
                                response_model=RestfulModel[PageInfo[ViolationConverted]],
                                summary='违章信息')
async def get_violation_detail(page_num: Optional[int] = Query(1, title='页号', alias='pageNum'),
                               page_size: Optional[int] = Query(50, title='一页多少数据', alias='pageSize'),
                               keyword: Optional[str] = Query(None, title='查询关键字', description='对 description 字段进行查询'),
                               mysql_db: Database = Depends(get_mysql_db)):
    offset = (page_num - 1) * page_size
    # 查询 list 部分
    select_stmt = select(ViolationInDb)
    if keyword:
        select_stmt = select_stmt.filter(ViolationInDb.description.like(f'%{keyword}%'))
    statement = select_stmt.order_by(desc(ViolationInDb.update_time)).offset(offset).limit(page_size)
    violation_list = await mysql_db.fetch_all(statement)
    violation_list = [PostProcessViolation.convert_violation(ViolationInDb(**violation)) for violation in violation_list]
    # 查询 total 部分
    total_query_stmt = select([func.count()]).select_from(ViolationInDb)
    if keyword:
        total_query_stmt = total_query_stmt.filter(ViolationInDb.description.like(f'%{keyword}%'))
    total_cnt = await mysql_db.fetch_val(total_query_stmt)
    return RestfulModel.success(PageInfo(total=total_cnt, list=violation_list))


@drive_action_detail_router.get('/complaint',
                                response_model=RestfulModel[PageInfo[ComplaintConverted]],
                                summary='用户投诉')
async def get_compliant_detail(page_num: Optional[int] = Query(1, title='页号', alias='pageNum'),
                               page_size: Optional[int] = Query(50, title='一页多少数据', alias='pageSize'),
                               keyword: Optional[str] = Query(None, title='查询关键字'),
                               mysql_db: Database = Depends(get_mysql_db)):
    offset = (page_num - 1) * page_size
    # 查询 list 部分
    select_stmt = select(ComplaintInDb)
    if keyword:
        select_stmt = select_stmt.filter(ComplaintInDb.reason.like(f'%{keyword}%'))
    statement = select_stmt.order_by(desc(ComplaintInDb.update_time)).offset(offset).limit(page_size)
    complaint_list = await mysql_db.fetch_all(statement)
    complaint_list = [PostProcessComplaint.convert_complaint(ComplaintInDb(**complaint)) for complaint in complaint_list]
    # 查询 total 部分
    total_query_stmt = select([func.count()]).select_from(ComplaintInDb)
    if keyword:
        total_query_stmt = total_query_stmt.filter(ComplaintInDb.reason.like(f'%{keyword}%'))
    total_cnt = await mysql_db.fetch_val(total_query_stmt)
    return RestfulModel.success(PageInfo(total=total_cnt, list=complaint_list))
